package fetcher

import (
	"bufio"
	"fmt"
	"golang.org/x/net/html/charset"
	"golang.org/x/text/encoding"
	"golang.org/x/text/encoding/unicode"
	"golang.org/x/text/transform"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func Fetch(url string) ([]byte, error) {
	resp, err := http.Get(url)
	time.Sleep(200 * time.Microsecond)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	//eBad:=determineEncodingBad(resp.Body)

	bodyReader := bufio.NewReader(resp.Body)
	e := determineEncoding(bodyReader)
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("wrong status code:%d", resp.StatusCode)
	}
	utf8Reader := transform.NewReader(bodyReader, e.NewDecoder())
	return ioutil.ReadAll(utf8Reader)
}

/**
 注意这里peek1024之后，再次调用上面的是从 1025字节之后才读的
transform.NewReader
*/
func determineEncodingBad(r io.Reader) encoding.Encoding {
	bytes, err := bufio.NewReader(r).Peek(1024)
	if err != nil {
		//暂且返回默认的
		log.Printf("fetcher error %v", err)
		return unicode.UTF8
	}
	e, _, _ := charset.DetermineEncoding(bytes, "")
	return e
}
func determineEncoding(r *bufio.Reader) encoding.Encoding {
	bytes, err := r.Peek(1024)
	if err != nil {
		//暂且返回默认的
		log.Printf("fetcher error %v", err)
		return unicode.UTF8
	}
	e, _, _ := charset.DetermineEncoding(bytes, "")
	return e
}
